package cn.cqie.frame.utils;

import cn.cqie.frame.entity.SysUser;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @author xieyihong
 */
public class TokenUtil {
    private static final long EXPIRE_TIME = 3 * 60 * 60 * 1000;
    //密钥盐
    private static final String TOKEN_SECRET = "token123";
    private static final String ISSUER = "auth0";
    private static final String CLAIM_KEY_USER_ID = "user_id";

    /**
     * 生成token 的方法
     *
     * @param user
     * @return
     */
    public static String sign(SysUser user) {
        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer(ISSUER)
                    .withClaim(CLAIM_KEY_USER_ID, user.getId())
                    .withExpiresAt(expiresAt)
                    // 使用了HMAC256加密算法。
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 签名验证
     *
     * @param token
     * @return
     */
    public static Long verify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer(ISSUER).build();
            DecodedJWT jwt = verifier.verify(token);
            Long userId = jwt.getClaim(CLAIM_KEY_USER_ID).asLong();
            System.out.println(userId);
            System.out.println("认证通过：");
            System.out.println("issuer: " + jwt.getIssuer());
            System.out.println("userId: " + userId);
            System.out.println("过期时间：      " + jwt.getExpiresAt());
            return userId;
        } catch (Exception e) {
            return null;
        }

    }


}
